package com.example.healing.controller;

import cn.hutool.core.map.MapUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.server.HttpServerRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.healing.common.lang.Result;
import com.example.healing.entity.User;
import com.example.healing.service.UserService;
import com.example.healing.shiro.JwtToken;
import com.example.healing.util.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import javax.servlet.http.HttpServletResponse;

@EnableSwagger2
@RestController
@Api(tags = "用户")
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtils jwtUtils;

    @GetMapping("/toLogin")
    public Result toLogin() {
        return Result.fail("请先登录！");
    }


    @ApiOperation(value = "用户注册")
    @PostMapping("/create")
    public Result create(@Validated @RequestBody @ApiParam("用户注册信息") User user) {
        user.setPassword(SecureUtil.md5(user.getPassword()));
        int res = userService.create(user);
        return res == -1 ? Result.fail("注册失败") : Result.succ(user.getLoginname());
    }

    @ApiOperation(value = "用户登录")
    @PostMapping("/login")
    public Result login(@Validated @RequestBody @ApiParam("用户实体、帐号密码") User user, HttpServletResponse response) {
        User u = userService.getOne(new QueryWrapper<User>().eq("loginname", user.getLoginname()));
        Assert.notNull(u, "用户不存在");

        if(!u.getPassword().equals(SecureUtil.md5(user.getPassword()))){
            return Result.fail("密码不正确");
        }
        String jwt = jwtUtils.generateToken(u.getUid());

        response.setHeader("Authorization", jwt);
        response.setHeader("Access-control-Expose-Headers", "Authorization");
        return Result.succ(MapUtil.builder()
                .put("uid", u.getUid())
                .put("username", u.getUsername())
                .put("loginname", u.getLoginname())
                .put("avatar", u.getAvatar())
                .put("gender", u.getGender())
                .map()
        );
    }

    @ApiOperation(value = "退出登录（需要带token）")
    @RequiresAuthentication
    @GetMapping("/logout")
    public Result logout() {
        SecurityUtils.getSubject().logout();
        return Result.succ("已退出登录");
    }

    @RequiresAuthentication
    @ApiOperation(value = "修改用户信息（需要带token）")
    @PutMapping("/edit")
    public Result edit (@RequestBody @ApiParam("用户信息") User user, HttpServerRequest request) {
        User curUser = (User) SecurityUtils.getSubject().getPrincipal();
        user.setUid(curUser.getUid());
        String ps = user.getPassword();
        if (!StringUtils.isEmpty(ps)) {
            user.setPassword(SecureUtil.md5(ps));
        }
        if ("".equals(ps)) {
            user.setPassword(null);
        }
        int res = userService.edit(user);
        return res == 1 ? Result.succ("修改成功") : Result.fail("修改失败");
    }

    @ApiOperation(value = "校验用户注册信息")
    @GetMapping("/verifyLoginName")
    public Result verifyLoginName(@RequestParam @ApiParam("用户登录名") String loginname) {
        User u = userService.getUser(loginname);
        return u == null ? Result.succ("可以创建") : Result.fail("登录名已存在");
    }
}
